'''Program for generating a cheat sheet PDF out of xml files'''

from reportlab.lib.units import cm
from reportlab.platypus import Paragraph #SimpleDocTemplate, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER
from reportlab.lib.colors import *

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4

import xml.etree.ElementTree as ElementTree
import settings

from text_processor import process_string


class PDFBuilder():
    """Class for building the pdf"""
    x_offset = 0
    y_offset = A4[1]

    color1 = Color(0, 0, 0)
    color1_r = 0.0
    color1_g = 0.0
    color1_b = 0.0

    color2 = Color(0, 0, 0)
    color2_r = 0.0
    color2_g = 0.0
    color2_b = 0.0

    maxwidth = 0.0
    usedwidth = 0.0



    headeroffset = A4[1] - 3.6*cm
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    pdffile = canvas.Canvas("")

    def __init__(self):
        pass

    def initializePDF(self, title, nocolums):
        """Initialize PDF"""
        self.color1 = settings.settingslist["doc_color1"]
        self.color1_r = float(int(self.color1[2:4], 16))
        self.color1_g = float(int(self.color1[4:6], 16))
        self.color1_b = float(int(self.color1[6:8], 16))
        self.color2 = settings.settingslist["doc_color2"]
        self.color2_r = float(int(self.color2[2:4], 16))
        self.color2_g = float(int(self.color2[4:6], 16))
        self.color2_b = float(int(self.color2[6:8], 16))

        self.pdffile = canvas.Canvas("{sheet}.pdf".format(sheet=title), pagesize=A4)
        self.maxwidth = A4[0]/nocolums

        self.usedwidth = self.maxwidth - (0.5 * cm)

    def drawHeader(self, title):
        """Draws header in PDF"""

        self.pdffile.setFillColorRGB(self.color1_r/256, self.color1_g/256, self.color1_b/256)
        self.pdffile.roundRect(self.x_offset + 0.15*cm, self.y_offset - 3.3* cm, A4[0]-0.3*cm, 3*cm, 2,  fill=1, stroke=0)

        p = Paragraph("<font color=\"{color}\" size=\"36\">{title}</font>".format(color="#FFFFFF", title=title), self.styles["Center"])
        p.wrapOn(self.pdffile, A4[0] - 0.3*cm, 3*cm)
        p.drawOn(self.pdffile, self.x_offset + 0.15*cm, self.y_offset - 1.5 * cm)

        self.y_offset = self.y_offset - 3.6 * cm

    def drawTitle(self, title):
        """Prepare title of content block"""
        p = Paragraph("<font color=\"{color}\">{title}</font>".format(color=self.color2, title=title), self.styles["Center"])
        width, height = p.wrapOn(self.pdffile, self.usedwidth, 30*cm)

        #Draw rounded rect of title block + draw text in block
        self.pdffile.setFillColor(Color(self.color1_r/256, self.color1_g/256, self.color1_b/256))
        self.pdffile.roundRect(self.x_offset + 0.25*cm, self.y_offset - height - 0.5*cm, width, height + 0.5*cm, 2,  fill=1, stroke=0)
        p.drawOn(self.pdffile, self.x_offset + 0.25*cm, self.y_offset - height - 0.25*cm)
        self.y_offset = self.y_offset - height - 0.46*cm


    def drawCol1(self, title, root):
        '''Function for drawing the 1-column content block'''

        #Draw title block
        self.drawTitle(title)

        #Draw each column
        toggle = 1
        for row in root.findall("row"):
            row_string = ElementTree.tostring(row, 'utf-8').strip()[8:-9]
            row_string = process_string(row_string)
            print(row_string)

            rowtext = Paragraph("<font color=\"{color}\">{text}</font>".format(color="#272722", text=row_string), self.styles["Normal"])
            rowwidth, rowheight = rowtext.wrapOn(self.pdffile, self.usedwidth, 30*cm)

            if toggle is 1:
                self.pdffile.setFillColor(white)
                toggle = 0
            else:
                self.pdffile.setFillColor(Color(self.color2_r/256, self.color2_g/256, self.color2_b/256))
                toggle = 1

            self.pdffile.rect(self.x_offset + 0.25*cm, self.y_offset - rowheight - 0.3*cm, rowwidth, rowheight + 0.3*cm, fill = 1, stroke = 0)
            rowtext.drawOn(self.pdffile, self.x_offset + 0.3*cm, self.y_offset - rowheight - 0.15*cm)
            self.y_offset = self.y_offset - rowheight - 0.3*cm
        self.pdffile.setFillColor(Color(self.color1_r/256, self.color1_g/256, self.color1_b/256))
        self.pdffile.rect(self.x_offset + 0.25*cm, self.y_offset - 0.1 * cm, self.usedwidth, 0.1*cm, fill = 1, stroke = 0)
        self.y_offset = self.y_offset - 1*cm

    def drawCol2(self, title, root):
        '''Function for drawing the 2-column content block'''

        #Draw title block
        self.drawTitle(title)

        #Draw each row
        col1 = root.find("col1width").text
        col2 = root.find("col2width").text
        #Draw each column
        toggle = 1
        for row in root.findall("row"):
            if toggle is 1:
                self.pdffile.setFillColor(white)
                toggle = 0
            else:
                self.pdffile.setFillColor(Color(self.color2_r/256, self.color2_g/256, self.color2_b/256))
                toggle = 1

            columns = row.findall("column")
            if len(columns) is 1:
                string1 = ElementTree.tostring(columns[0]).strip()[8:-9]

                col1text = Paragraph("<font color=\"{color}\">{text}</font>".format(color="#272722", text=string1), self.styles["Normal"])
                col1dim = col1text.wrapOn(self.pdffile, self.usedwidth, 30*cm)

                height = col1dim[1]

                self.pdffile.rect(self.x_offset + 0.25*cm, self.y_offset - height - 0.3*cm, self.usedwidth, height + 0.3*cm, fill = 1, stroke = 0)
                col1text.drawOn(self.pdffile, self.x_offset + 0.3*cm, self.y_offset - height - 0.15*cm)
                self.y_offset = self.y_offset - height - 0.3*cm
            if len(columns) is 2:
                string1 = ElementTree.tostring(columns[0]).strip()[8:-9]
                string2 = ElementTree.tostring(columns[1]).strip()[8:-9]

                col1text = Paragraph("<font color=\"{color}\">{text}</font>".format(color="#272722", text=string1), self.styles["Normal"])
                col1dim = col1text.wrapOn(self.pdffile, self.usedwidth*float(col1), 30*cm)

                col2text = Paragraph("<font color=\"{color}\">{text}</font>".format(color="#272722", text=string2), self.styles["Normal"])
                col2dim = col2text.wrapOn(self.pdffile, self.usedwidth*float(col2), 30*cm)

                height = max(col1dim[1], col2dim[1])

                self.pdffile.rect(self.x_offset + 0.25*cm, self.y_offset - height - 0.3*cm, self.usedwidth, height + 0.3*cm, fill = 1, stroke = 0)
                col1text.drawOn(self.pdffile, self.x_offset + 0.3*cm, self.y_offset - height - 0.15*cm)
                col2text.drawOn(self.pdffile, self.x_offset + 0.3*cm + float(col1)*self.usedwidth, self.y_offset - height - 0.15*cm)
                self.y_offset = self.y_offset - height - 0.3*cm

        self.pdffile.setFillColor(Color(self.color1_r/256, self.color1_g/256, self.color1_b/256))
        self.pdffile.rect(self.x_offset + 0.25*cm, self.y_offset - 0.1 * cm, self.usedwidth, 0.1*cm, fill = 1, stroke = 0)
        self.y_offset = self.y_offset - 1*cm

    def drawText(self, title, root):
        '''Function for drawing the Text content block'''

        #Draw title block
        self.drawTitle(title)

        #Set background color
        self.pdffile.setFillColor(Color(self.color2_r/256, self.color2_g/256, self.color2_b/256))

        text = root.find("text")
        textstring = ElementTree.tostring(text).strip()

        textstring = process_string(textstring)

        blocktext = Paragraph("<font color=\"{color}\">{text}</font>".format(color="#272722", text=textstring), self.styles["Normal"])
        blockdim = blocktext.wrapOn(self.pdffile, self.usedwidth, 30*cm)
        height = blockdim[1]

        #Draw text
        self.pdffile.rect(self.x_offset + 0.25*cm, self.y_offset - height - 0.3*cm, self.usedwidth, height + 0.3*cm, fill = 1, stroke = 0)
        blocktext.drawOn(self.pdffile, self.x_offset + 0.3*cm, self.y_offset - height - 0.15*cm)
        self.y_offset = self.y_offset - height - 0.3*cm

        #Draw footer
        self.pdffile.setFillColor(Color(self.color1_r/256, self.color1_g/256, self.color1_b/256))
        self.pdffile.rect(self.x_offset + 0.25*cm, self.y_offset - 0.1 * cm, self.usedwidth, 0.1*cm, fill = 1, stroke = 0)

        #Offset for next module
        self.y_offset = self.y_offset - 1*cm



    def drawModule(self, module):
        '''Reads the XML file for a given module and print on PDF'''
        tree = ElementTree.parse("cheatsheets/modules/{name}.xml".format(name=module))
        root = tree.getroot()
        contenttype = root.find("type")

        if contenttype is not None:
            contenttypetext = contenttype.text
            print(contenttypetext)
            if contenttypetext == "col1" or contenttypetext == "col2" or contenttypetext == "text":
                title = root.find("title")
                if title is not None:
                    if contenttypetext == "col1":
                        self.drawCol1(title.text, root)
                    elif contenttypetext == "col2":
                        self.drawCol2(title.text, root)
                    elif contenttypetext == "text":
                        self.drawText(title.text, root)
                        



    def nextcolumn(self):
        '''Jump to next column'''
        self.x_offset = self.x_offset + self.maxwidth
        self.y_offset = self.headeroffset

    def save(self):
        '''Save PDF file'''
        self.pdffile.save()